package com.mot.st.network

import android.util.Log
import com.ald.plane_tool.Constant
import com.aleyn.mvvm.BuildConfig
import com.aleyn.mvvm.network.interceptor.Level
import com.aleyn.mvvm.network.interceptor.LoggingInterceptor
import com.google.gson.GsonBuilder

import com.ksck.logoDesign.app.network.request.ParamInterceptor

import com.ksck.logoDesign.app.network.request.TokenInterceptor
import okhttp3.ConnectionPool
import okhttp3.OkHttpClient
import okhttp3.internal.platform.Platform
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit


/**
 *   @auther : Aleyn
 *   time   : 2019/09/04
 */
class RetrofitClient {

    companion object {
        fun getInstance() = SingletonHolder.INSTANCE
        private lateinit var retrofit: Retrofit
        val BASE_URL = if (BuildConfig.DEBUG)
        //开发
            Constant.url_release
        else
        //  "https://appluyin.kschuangku.com/api/"
            Constant.url_release
    }

    private object SingletonHolder {
        val INSTANCE = RetrofitClient()
    }

    init {
        val gson = GsonBuilder()
            .serializeNulls()
//            .registerTypeAdapter(String::class.java, StringAdapter::class.java)
            .registerTypeAdapterFactory(NullStringToEmptyAdapterFactory<String>())
            .create()

        retrofit = Retrofit.Builder()
            .client(getOkHttpClient())

            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create(gson))
//            .addConverterFactory(MyGsonConverterFactory.create())
            .build()




    }

    private fun getOkHttpClient(): OkHttpClient {

        return OkHttpClient.Builder()
            .retryOnConnectionFailure(true)//默认重试一次，若需要重试N次，则要实现拦截器。
            .connectTimeout(30L, TimeUnit.SECONDS)

            .addNetworkInterceptor(LoggingInterceptor().apply {
                isDebug = BuildConfig.DEBUG
                level = Level.BASIC
                type = Platform.INFO
                requestTag = "Request"
                requestTag = "Response"
            })
            .writeTimeout(30L, TimeUnit.SECONDS)
            .connectionPool(ConnectionPool(8, 15, TimeUnit.SECONDS))
            .addInterceptor(ParamInterceptor())
//            .addInterceptor(TokenInterceptor())
            .build()

    }

    fun <T> create(service: Class<T>?): T =
        retrofit.create(service!!) ?: throw RuntimeException("Api service is null!")

}

